#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import argparse
import subprocess
import shutil

def parse_args():
    p = argparse.ArgumentParser(
        description="将已经生成好的 base-<distro>.yaml / python-<distro>.yaml 安装到 /etc/ros/rosdep 并 rosdep update"
    )
    p.add_argument("--distro", required=True,
                   help="与生成文件对应的发行版标识 (例如 openeuler, mylinux等), 用于创建 sources.list.d/<distro>-custom.list")
    p.add_argument("--base-yaml", required=True,
                   help="base-<distro>.yaml 文件路径")
    p.add_argument("--python-yaml", required=True,
                   help="python-<distro>.yaml 文件路径")
    return p.parse_args()

def main():
    args = parse_args()

    # 1. 检查文件是否存在
    if not os.path.isfile(args.base_yaml):
        print(f"[ERROR] base yaml 不存在: {args.base_yaml}")
        sys.exit(1)
    if not os.path.isfile(args.python_yaml):
        print(f"[ERROR] python yaml 不存在: {args.python_yaml}")
        sys.exit(1)

    # 2. 需要root权限写 /etc/ros/rosdep
    if os.geteuid() != 0:
        print("[WARN] 当前不是 root, 正在尝试sudo...")
        new_argv = sys.argv[1:]
        subprocess.check_call(["sudo", sys.executable, __file__] + new_argv)
        sys.exit(0)  # 结束当前进程

    custom_dir = "/etc/ros/rosdep/custom"
    os.makedirs(custom_dir, exist_ok=True)

    def copy_to_custom(src):
        dst = os.path.join(custom_dir, os.path.basename(src))
        shutil.copyfile(src, dst)
        return dst

    # 3. 拷贝 base-yaml & python-yaml
    print(f"[INFO] 复制 {args.base_yaml} => {custom_dir}")
    base_dst = copy_to_custom(args.base_yaml)
    print(f"[INFO] 复制 {args.python_yaml} => {custom_dir}")
    py_dst   = copy_to_custom(args.python_yaml)

    # 4. 写 sources.list
    list_file = f"/etc/ros/rosdep/sources.list.d/{args.distro}-custom.list"
    print(f"[INFO] 写入 sources.list: {list_file}")
    with open(list_file, "w", encoding="utf-8") as f:
        f.write(f"yaml file://{base_dst}\n")
        f.write(f"yaml file://{py_dst}\n")

    # 5. rosdep update
    print("[INFO] rosdep update...")
    ret = subprocess.run(["rosdep", "update"])
    if ret.returncode == 0:
        print("[INFO] rosdep update 成功.")
    else:
        print(f"[WARN] rosdep update 失败，returncode={ret.returncode}")

    print("[INFO] 脚本执行完毕.")

if __name__=="__main__":
    main()
















